package cn.demo.text.editor.panel;

import javax.swing.*;
import javax.swing.text.Element;
import java.awt.*;

public class LineNumberPanel extends JPanel {
    private final JTextArea textArea;

    public LineNumberPanel(JTextArea textArea) {
        this.textArea = textArea;
        textArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                repaint();
            }

            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
                repaint();
            }

            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.GRAY);
        g2d.setFont(new Font("Monospaced", Font.PLAIN, 12));

        int lineHeight = textArea.getFontMetrics(textArea.getFont()).getHeight();
        int startOffset = textArea.getInsets().top;

        Element root = textArea.getDocument().getDefaultRootElement();
        int lineCount = root.getElementCount();

        for (int i = 0; i < lineCount; i++) {
            int y = startOffset + (i + 1) * lineHeight - 4;
            g2d.drawString(String.valueOf(i + 1), 5, y);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(30, textArea.getHeight());
    }
}